#include "bfsalgorithm.h"
#include "node.h"

#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QDebug>

BFSAlgorithm::BFSAlgorithm()
{
    m_nodeList.clear();
}

void BFSAlgorithm::searchPath(QGraphicsScene *pScene, Node *pFromNode)
{
    QList<QGraphicsItem *> itemList = pScene->items();

    foreach(QGraphicsItem *pItem, itemList)
    {
        Node *pNode = dynamic_cast<Node *>(pItem);
        if(NULL == pNode)
        {
            qDebug() << "["  << __FUNCTION__ << "]: error";
            continue;
        }
        pNode->setSearchStatus(Node::NotFind);
        pNode->setSearchDepth(-1);
        pNode->setParentItem(NULL);
    }

    pFromNode->setSearchStatus(Node::FindSide);
    pFromNode->setSearchDepth(0);
    pFromNode->setParentItem(NULL);

    QList<Node *> nodeList;
    nodeList.clear();
    nodeList.append(pFromNode);

    while(!nodeList.isEmpty())
    {
        Node *pParentNode = nodeList.takeFirst();
        qDebug() << "Parent Node: " << pParentNode->text();
        QSet<Node *> neighbourNodeSet = pParentNode->getNeighbourSet();
        foreach(Node *pChildNode, neighbourNodeSet)
        {

            if(Node::NotFind == pChildNode->getSearchStatus())
            {
                qDebug() << "[" << pParentNode->getSearchDepth() << "]: "
                         << pChildNode->text();
                pChildNode->setSearchStatus(Node::FindSide);
                pChildNode->setSearchDepth(
                            pParentNode->getSearchDepth() + 1);
                pChildNode->setParentItem(pParentNode);
                nodeList.append(pChildNode);
            }
        }
        pParentNode->setSearchStatus(Node::AllFind);
    }
}

void BFSAlgorithm::printPath(QGraphicsScene *pScene, Node *pFromNode, Node *pToNode)
{
    searchPath(pScene, pFromNode);
    findPath(pFromNode, pToNode);
    if(m_nodeList.isEmpty())
    {
        qDebug() << "No path from: " << pFromNode->text() << "to "
                 << pToNode->text() << " exists";
        return;
    }
    else
    {
        QString strPath = "";
        foreach(Node *pNode, m_nodeList)
        {
            strPath += pNode->text() + "-";
        }
        strPath += pFromNode->text();
        qDebug() << "Path" << strPath;
        return;
    }
}

void BFSAlgorithm::findPath(Node *pFromNode, Node *pToNode)
{
    if(pFromNode->id() == pToNode->id())
    {
        return;
    }
    else if(pToNode->getParentItem() == NULL)
    {
        return;
    }
    else
    {
        m_nodeList.append(pToNode);
        findPath(pFromNode, pToNode->getParentItem());
        return;
    }
}


